import { useActiveObject } from '@/store/activeObject'
import { useAuthStore } from '@/store/auth'
import { useViewportStore } from '@/store/viewport'
import emiter from '@/utils/mitt'
import { useAddTools } from '@/utils/useAddTools'
import { useFocusObject } from '@/utils/useFocusObject'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'

export default function () {
  const activeObjectStore = useActiveObject()
  const viewportStore = useViewportStore()
  const { focusObject } = useFocusObject()
  const { publicGroup } = storeToRefs(viewportStore)
  const { hasGroup } = useAddTools()
  const authStore = useAuthStore()
  const { modeParams } = storeToRefs(authStore)
  // 根据错误提示，调整事件处理函数的类型，确保与 emiter 的 on 方法参数类型匹配
  emiter.on('areaChange', (ids) => {
    if (!ids) {
      activeObjectStore.setActiveVO(null)
      const group = hasGroup('巷道', false)
      if (group) {
        focusObject(group)
      }
    } else {
      publicGroup.value?.children.forEach((group) => {
        if (group.name === '巷道') {
          let flag = false
          group.traverse((node) => {
            if (ids.includes(node.uuid)) {
              if (ids.length > 1 && node.parent.type === 'Group') {
                activeObjectStore.setActiveVO(node.parent)
                if (modeParams.value.model !== 'backtracking') {
                  focusObject(node.parent)
                }
              } else {
                activeObjectStore.setActiveVO(node)
                if (modeParams.value.model !== 'backtracking') {
                  focusObject(node.parent)
                }
              }
              flag = true
            }
          })
          if (!flag) {
            activeObjectStore.setActiveVO(null)
            const group = hasGroup('巷道', false)
            if (group) {
              focusObject(group)
            }
            ElMessage({
              message: '无匹配数据，如有疑问请联系管理员',
              type: 'warning'
            })
          }
        }
      })
    }
  })
}
